const nameExcludedWords = ["4k", "2160p", "1080p", "1080i",, "720p", "480p", "blurayrip", "brrip", "divx", "dvdrip", "hdrip", "hdtv", "tvrip", "xvid", "camrip"];
const yearMinMax = [1900, 2100];

function simplifyName(n) { 
    let name = n
                .toLowerCase()
                .trim()
                .replace(/\([^\(]+\)$/, "") // remove brackets at end
                .replace(/&/g, "and")
                .replace(/[^\u4e00-\u9fa50-9a-z ]+/g, " ") // remove special chars
                .split(" ").filter(function(r){return r}).join(" ")       
    const nameSplit = name.split(' ')
    if (/^[\u4e00-\u9fa5]+/.test(nameSplit[0])) name = nameSplit[0] // 有中文名只保留中文名称
    return name
};

// 只从种子名称中提取名称、年份、季数
// 使用场景，解析种子任务名称，进行TMDB搜索
function parseTorrentName(title, options={}) {
    if (!title) return;

    const meta = {};
    
    const titleRelaced = title.replace(/\.|;|_/g, ' ').replace(/\[|\]|\(|\)/g, ' ').trim();
    // console.log('titleRelaced', titleRelaced);
    const titleSplited = titleRelaced.split(' ').filter(function(r){return r});
    // console.log('titleSplited', titleSplited);

    // 1.解析名称
    const nameParts = [];
    titleSplited.some(function(word, i){
        /* words with basic punctuation and two-digit numbers; or numbers in the first position */
        if (
            nameExcludedWords[word.toLowerCase()]
            || ((["ep", "episode", "season"].indexOf(word.toLowerCase()) > -1) && !isNaN(titleSplited[i+1])) // TODO: more than that, match for stamp too
            || (i > 0 && /^s\d{1,2}[e\d{1,3}]?$/i.test(word))
            || !(word.match(/^[\u4e00-\u9fa5a-zA-Z,?!'&，？！]+\d{0,4}$/) || (!isNaN(word) && word.length <= 2) || (!isNaN(word) && i==0))
            )
            return true;

        nameParts.push(word);           
    });
    // console.log('nameParts', nameParts);
    if (nameParts.length == 1 && !isNaN(nameParts[0])) {
        meta.name = nameParts[0]
    } else {
        meta.name = nameParts
            .filter(function(x) { return x && x.length > 0 })
            // .map(function(x) { return x[0].toUpperCase() + x.slice(1).toLowerCase() })
            .join(" ");
    }

    // 优化名称，如只保留中文
    meta.name = meta.name && simplifyName(meta.name);

    // 2.解析年份
    const yearMatches = titleRelaced.match(/\b\d{4}\b/g)
    // console.log('yearMatches', yearMatches);
    if (yearMatches) {
        const tempYears = yearMatches.filter(function(year) {
            return year >= yearMinMax[0] && year <= yearMinMax[1];
        })
        // 有且只有一个年份
        if (tempYears.length == 1) meta.year = tempYears[0]
        // 有多个年份，取第二个
        if (tempYears.length >= 2) meta.year = tempYears[1]
    }

    // 解析季数
    var seasonMatch = titleRelaced.match(/\sS(\d{1,2})\s/i);
    // console.log('seasonMatch', seasonMatch);
    if (seasonMatch)
        meta.season = parseInt(seasonMatch[1], 10);
    var episodeMatch = titleRelaced.match(/\sS(\d{1,2})E(\d{1,4})\s/i);
    // console.log('episodeMatch', episodeMatch);
    if (episodeMatch) {
        meta.season = parseInt(episodeMatch[1], 10);
        meta.episodes = [parseInt(episodeMatch[2], 10)];
    }  
    
    if (meta.season === undefined || meta.episodes === undefined) {
        var episodeMatch2 = titleRelaced.match(/\sS(\d{1,2})E(\d{1,4})-(S\d{1,2})?E?(\d{1,4})\s/i);
        // console.log('episodeMatch2', episodeMatch2);
        if (episodeMatch2) {
            meta.season = parseInt(episodeMatch2[1], 10);
            meta.episodes = []
            // 从1到10生成数组
            for (let index = parseInt(episodeMatch2[2], 10); index <= parseInt(episodeMatch2[4], 10); index++) {
                meta.episodes.push(index)
            }
        }
    }   
    
    if (meta.season === undefined || meta.episodes === undefined) {
        var episodeMatch2 = titleRelaced.match(/\sEP(\d{1,4})-(EP)?(\d{1,4})\s/i);
        // console.log('episodeMatch2', episodeMatch2);
        if (episodeMatch2) {
            meta.season = 1;
            meta.episodes = []
            // 从1到10生成数组
            for (let index = parseInt(episodeMatch2[1], 10); index <= parseInt(episodeMatch2[3], 10); index++) {
                meta.episodes.push(index)
            }
        }
    } 

    // 解析分辨率
    meta.pix = getPix(titleSplited)
    // 解析视频编码
    meta.videoEncode = getVideoEncode(title)
    // 解析视频媒介
    meta.videoMedium = getVideoMedium(titleSplited)
    // 解析音频编码
    meta.audioEncode = getAudioEncode(titleSplited)
    // 解析制作组
    meta.group = getGroup(titleSplited)
    return meta;
}

// 解析分辨率
const pixMap = {
    '2160p': /2160p|4k|UHD/i,
    '1080p': /1080[p|i]/i,
    '720p': /720[p|i]/i,
}
function getPix(titleSplited) {
    for (const pix in pixMap) {
        for (let index = 0; index < titleSplited.length; index++) {
            const word = titleSplited[index];
            if (pixMap[pix].test(word)) return pix
        }
    }
}

// 解析视频编码
const videoEncodeMap = {
    'h265': /[H|X].?265|HEVC/i,
    'h264': /[H|X].?264|AVC/i,
}
function getVideoEncode(title) {
    for (const videoEncode in videoEncodeMap) {
        if (title.match(videoEncodeMap[videoEncode])) return videoEncode
    }
}


// 解析视频媒介
const videoMediumMap = {
    'WEB-DL': /WEB-?DL|WEB-?Rip/i,
    'BluRay': /Blu-?Ray/i,
    'Remux': /Remux/i,
    'DVD': /DVD/i,
}
function getVideoMedium(titleSplited) {
    const videoMediums = []
    for (const videoMedium in videoMediumMap) {
        for (let index = 0; index < titleSplited.length; index++) {
            const word = titleSplited[index];
            if (videoMediumMap[videoMedium].test(word)) videoMediums.push(videoMedium)
        }
    }
    return videoMediums
}


// 解析音频编码
const audioEncodeReg = /^DTS\d?$|^DTS-?HD$|^DTSHDMA$|^Atmos$|^TrueHD\d?$|^AC3$|^\dAudios?$|^DDP\d?$|^DD\d?$|^LPCM\d?$|^AAC\d?$|^FLAC\d?$|^HD\d?$|^MA\d?$/i;
function getAudioEncode(titleSplited) {
    const audioEncodes = []
    for (let index = 0; index < titleSplited.length; index++) {
        const word = titleSplited[index];
        const matched = audioEncodeReg.test(word)
        if (matched) audioEncodes.push(word)
    }
    return audioEncodes
}

// 解析制作组
const groupReg = /(MTeam|CNHK|BTSCHOOL|BtsTV|BtsHD|QHstudIo|DBTV|FRDS)+/i;
function getGroup(titleSplited) {
    // for (let index = 0; index < titleSplited.length; index++) {
    //     const word = titleSplited[index];
    //     const matched = word.match(groupReg)
    //     if (matched) return matched[1]
    // }
    // 只判断最后的一个单词
    const matched = titleSplited[titleSplited.length-1].match(groupReg)
    if (matched) return matched[1]
}





// rss副标题解析
const Nzh = require("nzh"); 
const nzh = new Nzh({
    ch: "零一二三四五六七八九",      // 数字字符
    ch_u: "个十百千万亿兆京",       // 数位单位字符，万以下十进制，万以上万进制，个位不能省略
    // ch_f: "负",                   // 负字符
    // ch_d: "点",                   // 小数点字符
    // m_u: "元角分厘",              // 金额单位
    // m_t: "人民币",                // 金额前缀
    // m_z: "正"                    // 金额无小数后缀
});
const isAllEpisodes = (title) => {
    const allEpisodesReg = /([0-9一二三四五六七八九十]+)\s*集全|全\s*([0-9一二三四五六七八九十]+)\s*集/i;
    const allEpisodesMatch = title.match(allEpisodesReg)
    // console.log("allEpisodesMatch", allEpisodesMatch);
    if (allEpisodesMatch) {
        return allEpisodesMatch[2]
    }
    return false
}
const getEpisodes = (title) => {
    let episodes = []
    let start,end;
    // 1. 全集判断
    const allEpisodes = isAllEpisodes(title)
    
    if (allEpisodes) {
        start = 1
        end = isNaN(allEpisodes) ? nzh.decode(allEpisodes) : parseInt(allEpisodes)
    } else {
        // 2. 集数判断
        const episodeReg = /(第|EP?)([0-9一二三四五六七八九十]+)(\-|到|至)?(第|EP?)?([0-9一二三四五六七八九十]+)?[集话話]/i;
        const episodeMatch = title.match(episodeReg)
        // console.log("episodeMatch", episodeMatch);
        if (episodeMatch) {
            start = episodeMatch[2]
            end = episodeMatch[5]
        }
    }
    
    if (start) {
        isNaN(start) ? start = nzh.decode(start) : start = parseInt(start)
        if (end) {
            isNaN(end) ? end = nzh.decode(end) : end = parseInt(end)
            for (let i = start; i <= end; i++) {
                episodes.push(i)
            }
        } else {
            episodes[0] = start
        }
    }

    return episodes;
} 


// 直接解析单季一般用于副标题
const getSeasonSingle = (title) => {
    let season
    // 1. 季数判断
    let seasonReg = /第([0-9一二三四五六七八九十]+)季/i;
    let seasonMatch = title.match(seasonReg)
    // console.log("seasonMatch", seasonMatch);
    if (seasonMatch) {
        season = seasonMatch[1]
        isNaN(season) ? season = nzh.decode(season) : season = parseInt(season)
    } else {
        seasonReg = /S(\d{1,2})/i
        seasonMatch = title.match(seasonReg)
        if (seasonMatch) {
            season = parseInt(seasonMatch[1])
        }
    }
    return season;
}

const getSeasons = (title) => {
    let seasons = []
    let start,end;
    
    // 1. 季数判断
    const seasonReg = /(第|S?)([0-9一二三四五六七八九十]+)(\-|到|至)?(第|S?)?([0-9一二三四五六七八九十]+)?季/i;
    const seasonMatch = title.match(seasonReg)
    // console.log("seasonMatch", seasonMatch);
    if (seasonMatch) {
        start = seasonMatch[2]
        end = seasonMatch[5]
    }
    
    if (start) {
        isNaN(start) ? start = nzh.decode(start) : start = parseInt(start)
        if (end) {
            isNaN(end) ? end = nzh.decode(end) : end = parseInt(end)
            for (let i = start; i <= end; i++) {
                seasons.push(i)
            }
        } else {
            seasons[0] = start
        }
    }

    return seasons;
}
const rssSubTitleParser = {
    isAllEpisodes, getEpisodes, getSeasons, getSeasonSingle
}

module.exports = {
    parseTorrentName, rssSubTitleParser
}